package ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;

import com.bumptech.glide.Glide;
import com.peng.auctionsystem.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import Widget.CustomToolBar;
import base.BaseActivity;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import entity.LoginEntity;
import entity.SavePictureEntity;
import kr.co.namee.permissiongen.PermissionGen;
import manager.ApiConstants;
import manager.ApiRequestManager;
import manager.RxSchedulers;
import manager.RxSubscriber;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import utils.BitmapUtils;
import utils.GlobalDataUtils;
import utils.ToastUtil;

public class ModifyInfoActivity extends BaseActivity implements CustomToolBar.OnToolBarClickListener {

    @Bind(R.id.custom_toolbar)
    CustomToolBar customToolbar;
    @Bind(R.id.modify_iv_avatar)
    ImageView modifyIvAvatar;
    @Bind(R.id.modify_et_nickname)
    EditText modifyEtNickname;
    @Bind(R.id.modify_rb_male)
    RadioButton modifyRbMale;
    @Bind(R.id.modify_rb_female)
    RadioButton modifyRbFemale;
    @Bind(R.id.radioGroup)
    RadioGroup radioGroup;
    @Bind(R.id.modify_btn_over)
    Button modifyBtnOver;
    @Bind(R.id.email_login_form)
    LinearLayout emailLoginForm;
    @Bind(R.id.login_form)
    ScrollView loginForm;

    public int REQUEST_IMAGE = 1;
    public int REQUEST_CODE_SDCARD = 2;
    private ArrayList<String> defaultDataArray = new ArrayList<>();
    private int id;
    private String sex;
    private String acount;
    private String pwd;
    private String nickName;
    private String headPortraitPath;
    private boolean hasModifyHead;// 是否修改过头像

    @Override
    public int getLayoutId() {
        return R.layout.activity_modify_info;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        customToolbar.findTextView(R.id.left_tv).setVisibility(View.GONE);
        customToolbar.findImageView(R.id.left_iv).setVisibility(View.VISIBLE);
        customToolbar.findTextView(R.id.right_tv_main).setVisibility(View.GONE);
        customToolbar.findTextView(R.id.right_tv_sub).setVisibility(View.GONE);
        customToolbar.findTextView(R.id.center_tv).setText("编辑个人信息");
        customToolbar.setOnCustomToolBarClickListener(this);

        LoginEntity user = GlobalDataUtils.getCurUser();
        Glide.with(this).load(user.getData().getPicturePath()).into(modifyIvAvatar);
        modifyEtNickname.setText(user.getData().getName());
        id = user.getData().getId();
        acount = user.getData().getAccount();
        pwd = user.getData().getPassword();
        headPortraitPath = user.getData().getPicturePath();
        if (user.getData().getSex().equals("1")) {
            modifyRbMale.setChecked(true);
        } else {
            modifyRbFemale.setChecked(true);
        }
    }

    @OnClick({R.id.modify_iv_avatar, R.id.modify_btn_over})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.modify_iv_avatar:// 点击重新选择头像
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                    chooseImage();
                } else {
                    if (ContextCompat.checkSelfPermission(ModifyInfoActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                            == PackageManager.PERMISSION_GRANTED) {
                        chooseImage();
                    } else {
                        //申请权限
                        PermissionGen.with(ModifyInfoActivity.this)
                                .addRequestCode(REQUEST_CODE_SDCARD)
                                .permissions(Manifest.permission.READ_EXTERNAL_STORAGE)
                                .request();
                    }
                }
                break;
            case R.id.modify_btn_over:// 完成编辑

                nickName = modifyEtNickname.getText().toString();

                if (nickName == null || nickName.equals("")) {
                    ToastUtil.showShort("请输入昵称");
                    return;
                }
                if (headPortraitPath == null || headPortraitPath.equals("")) {
                    ToastUtil.showShort("设置头像");
                    return;
                }
                if (modifyRbMale.isChecked()) {
                    sex = "1";
                } else {
                    sex = "2";
                }
                if (hasModifyHead) {
                    // 上传头像
                    uploadingHeadPortrait(headPortraitPath);
                } else {
                    modifyUser(acount, pwd, headPortraitPath, nickName, sex, id);
                }

                break;
        }
    }

    /**
     * 上传头像
     */
    private void uploadingHeadPortrait(String headPortrait) {
        //File file = new File(headPortrait);

        String picPath = headPortrait.substring(headPortrait.length() - 5, headPortrait.length());
        File headFile = BitmapUtils.samplingRateCompress(headPortrait, new File(getSDPath() + "/" + picPath));

        if (headFile != null && headFile.exists() && headFile.length() > 0) {
            mRxManager.add(
                    ApiRequestManager.getInstance().uploadFile(headFile)
                            .compose(RxSchedulers.<SavePictureEntity>io_main())
                            .subscribe(new RxSubscriber<SavePictureEntity>(this) {
                                @Override
                                protected void _onNext(SavePictureEntity savePictureEntity) {
                                    //提交文件路径及相关信息
                                    modifyUser(acount, pwd, ApiConstants.STAGING_MOBILE_TICKET_HOST + "commodity/" + savePictureEntity.getData(), nickName, sex, id);
                                }

                                @Override
                                protected void _onError(String message) {

                                }
                            })
            );
        } else {
            ToastUtil.showShort("文件不存在！");
        }
    }

    public void modifyUser(String acount, String pwd, String headPortraitPath, String nickName, String sex, int id) {
        mRxManager.add(ApiRequestManager.getInstance().modify(acount, pwd, headPortraitPath, nickName, sex, id)
                .subscribe(new RxSubscriber<LoginEntity>(ModifyInfoActivity.this, "正在修改...", true, false) {
                    @Override
                    protected void _onNext(LoginEntity baseResult) {
                        SharedPreferences sPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sPreferences.edit();
                        editor.putInt("userId", baseResult.getData().getId());
                        //切记最后要使用commit方法将数据写入文件
                        editor.commit();

                        ToastUtil.showShort("修改成功");
                        GlobalDataUtils.saveCurUser(baseResult);
                        finish();
                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUtil.showShort("注册失败");
                    }
                }));
    }

    /**
     * 获取SDCard的路径
     *
     * @return
     */
    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }

    /**
     * 选择头像跳转
     */
    private void chooseImage() {
        Intent intent = new Intent(mContext, MultiImageSelectorActivity.class);
        // 是否显示调用相机拍照
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大图片选择数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
        // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        // 默认选择图片,回填选项(支持String ArrayList)
        intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, defaultDataArray);
        startActivityForResult(intent, REQUEST_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            // 获取返回的图片列表(存放的是图片路径)
            if (data != null) {
                hasModifyHead = true;
                List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                headPortraitPath = path.get(0);
                modifyIvAvatar.setImageBitmap(BitmapFactory.decodeFile(headPortraitPath));
            }
        }
    }

    @Override
    public void onTitleLeftClick(View view) {
        finish();
    }

    @Override
    public void onTitleCenterClick(View view) {

    }

    @Override
    public void onTitleRightClick(View view) {

    }

    @Override
    public void onTitleRightSubClick(View view) {

    }
}
